package controllers

import javax.inject.Inject
import play.api.mvc._
import tool._
import dao._
import models.Tables.PdfInfoRow
import org.joda.time.DateTime
import play.api.libs.json.Json
import utils.Utils

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import shared.pojo.Pojo.{IdData, UserNameData, ValidData}
import upickle.default._
import implicits.Implicits._
import shared.Shared
import shared.pojo.User.{ChangePassword, PdfInfo, UserIdData}

/** Created by yz on 2018/8/20
  */
class UserController @Inject() (
    cc: ControllerComponents,
    formTool: FormTool,
    userDao: UserDao,
    accountDao: AccountDao,
    tool: Tool,
    pdfInfoDao: PdfInfoDao
) extends AbstractController(cc) {

  def reduceTimes = Action.async { implicit request =>
    val name = tool.getUserName
    userDao
      .selectSomeByName(name)
      .flatMap { x =>
        val times = x.remainTimes.map { times =>
          if (times <= 0) 0 else times - 1
        }
        val row = x.copy(remainTimes = times)
        userDao.update(row)
      }
      .map { x =>
        Ok("success")
      }
  }

  def logout = Action { implicit request =>
    Ok("success")
//    .flashing("info" -> "退出登录成功!", "class" -> Utils.successClass).
//      removingFromSession(Shared.userStr)
  }

  def changePassword = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[ChangePassword.Request])
    userDao
      .selectByName(data.name)
      .flatMap { x =>
        val dbUser = x.get
        if (data.password == dbUser.password) {
          val row = UserData(data.name, data.newPassword)
          userDao.update(row).map { y =>
            ValidData(valid = true)
          }
        } else {
          Future {
            ValidData(valid = false)
          }
        }
      }
      .map { x =>
        Ok(writeJs(x))
      }

  }

  def getLimit = Action.async { implicit request =>
    val data=Tool.transformRq.transform(reader[UserNameData])
    userDao.selectSomeByName(data.name).map { user =>
      val b = tool.isb(user)
      Ok(Json.toJson(b))
    }
  }

  def detailInfo = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[UserIdData])
    userDao.selectById(data.id).map { x =>
      Ok(writeJs(x))
    }

  }

  def getPdfInfo = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[UserIdData])
    pdfInfoDao.selectById(data.id).map { x =>
      Ok(writeJs(x))
    }
  }

  def updatePdfInfo = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[PdfInfo])
    val pdfInfo =
      PdfInfoRow(data.userId, data.title, data.unit, data.address, data.reporter, data.checker)
    pdfInfoDao.update(pdfInfo).map { x =>
      val response = ValidData(valid = true)
      Ok(writeJs(response))
    }
  }

}
